import classnames from 'classnames'
import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { Article } from '@/store/reducer/search'
import { Image } from 'antd-mobile'
import { hasToken } from '@/utils/storage'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { useDispatch } from 'react-redux'
import { setArticleMarkAPI } from '@/store/action/article'
import history from '@/utils/history'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

// 定义传过来的数据类型
interface Props
  extends React.DetailedHTMLProps<
    React.HTMLAttributes<HTMLDivElement>,
    HTMLDivElement
  > {
  article: Article
  className?: string
}

export default function ArticleItem({ className, article, ...rest }: Props) {
  // 解构出封面类型 和图片
  const { type, images } = article.cover

  const dispatch = useDispatch()
  // 点击打开文章标记
  const handelSetMark = () => {
    // 传入文章对应的id
    dispatch(setArticleMarkAPI({ visible: true, article_id: article.art_id }))
  }

  return (
    <div {...rest} className={classnames(styles.root, className)}>
      {/* t3: 三图结构 none-mt没有图片结构  */}
      <div
        onClick={() => history.push(`/article/${article.art_id}`)}
        className={classnames('article-content', {
          t3: type === 3,
          'none-mt': type === 0,
        })}
      >
        <h3>{article.title}</h3>
        {/* 非 0 表示有图片 */}
        {type !== 0 && (
          <div className="article-imgs">
            {images.map((item, index) => (
              <div key={index} className="article-img-wrapper">
                <Image lazy fit="cover" src={item} alt="" />
              </div>
            ))}
          </div>
        )}
      </div>
      <div className={classnames('article-info', type === 0 ? 'none-mt' : '')}>
        <span>{article.aut_name}</span>
        <span>{article.comm_count}评论</span>
        <span>{dayjs(article.pubdate).fromNow()}</span>
        {/* 短路运算 && 前面为ture 则执行后面的结果 */}
        {hasToken() && (
          <span className="close" onClick={handelSetMark}>
            <Icon type="iconbtn_essay_close" />
          </span>
        )}
      </div>
    </div>
  )
}
